'''
Created on 2011-1-24

@author: siqi
'''
import os, string, DescriptionParser, ParseTheMapUsingOpenTTDExecutable
from Configuration import Configuration

cf = Configuration()
name = ["companyId", "Number of Vehicles", "Number of Profitable Vehicles", "Number of Servicing Stations", "Min income", "Max income", "Number of Delivered Cargo", "Score of Cargo", "Score of Money",
                "Score of Loan", "Total Score", "Value of Company", "Year", "Loan", "Number of Trains", "Number of Lorries", "Number of Busses", "Number of Planes", "Number of Ships"]

class SaveFileResult:
    def __init__(self):
        self.data = []
        self.read = False;
        self.companyId = 0; self.companyIds = []
        self.totalVehicle = 0; self.totalVehicles = []
        self.totalProfitingVehicle = 0; self.totalProfitingVehicles = []
        self.service_station= 0; self.service_stations = []
        self.min_income= 0; self.min_incomes = []
        self.max_income= 0; self.max_incomes = []
        self.cargo_delivered= 0; self.cargo_delivereds = []
        self.score_cargo= 0; self.score_cargos = []
        self.score_money= 0; self.score_moneys = []
        self.score_loan= 0;  self.score_loans = [] 
        self.score_total= 0; self.score_totals = []
        self.companyValue= 0; self.companyValues = []
        self.year = 0; self.years=[];
        self.loan = 0; self.loans=[];
        self.train = 0; self.trains=[];
        self.lorry =0; self.lorries = [];
        self.bus= 0; self.busses=[];
        self.plane=0; self.planes=[];
        self.ship=0; self.ships=[];
        self.datas = {0:self.companyIds, 1:self.totalVehicles, 2:self.totalProfitingVehicles, 3:self.service_stations, 
                      4:self.min_incomes, 5:self.max_incomes, 6:self.cargo_delivereds, 7:self.score_cargos, 
                      8:self.score_moneys, 9:self.score_loans, 10:self.score_totals, 11:self.companyValues,
                      12:self.years, 13:self.loans, 14:self.trains, 15:self.lorries, 16:self.busses, 17:self.planes, 18:self.ships};
#    def parseSaveFileResult(self, filename): #only works for old format
#        try:
#            file = open(filename)
#            lines = file.readlines()
#            pos = 0
#            offset = 0
#            while(True):
##                if pos > 0:
##                    offset = 1
##                print
#                self.companyId = string.atoi(lines[pos*11 + 1 + offset]); self.data.append(self.companyId); self.companyIds.append(self.companyId)
#                tup = string.split(lines[pos*11 + 2+ offset])
#                self.totalVehicle = string.atoi(tup[0]); self.data.append(self.totalVehicle); self.totalVehicles.append(self.totalVehicle)
#                self.totalProfitingVehicle = string.atoi(tup[1]);self.data.append(self.totalProfitingVehicle);self.totalProfitingVehicles.append(self.totalProfitingVehicle)
#                self.service_station = string.atoi(lines[pos*11 + 3+ offset]); self.data.append(self.service_station);self.service_stations.append(self.service_station)
#                tup = string.split(lines[pos*11 + 4+ offset])
#                self.min_income = string.atoi(tup[0]); self.data.append(self.min_income);self.min_incomes.append(self.min_income)
#                self.max_income = string.atoi(tup[1]); self.data.append(self.max_income);self.max_incomes.append(self.max_income)
#                self.cargo_delivered = string.atoi(lines[pos*11 + 5+ offset]); self.data.append(self.cargo_delivered);self.cargo_delivereds.append(self.cargo_delivered)
#                self.score_cargo = string.atoi(lines[pos*11 + 6+ offset]); self.data.append(self.score_cargo);self.score_cargos.append(self.score_cargo)
#                self.score_money = string.atoi(lines[pos*11 + 7+ offset]); self.data.append(self.score_money);self.score_moneys.append(self.score_money)
#                self.score_loan = string.atoi(lines[pos*11 + 8+ offset]); self.data.append(self.score_loan); self.score_loans.append(self.score_loan)
#                self.score_total = string.atoi(lines[pos*11 + 9+ offset]); self.data.append(self.score_total); self.score_totals.append(self.score_total)
#                self.companyValue = string.atoi(lines[pos*11 + 10+ offset][:lines[pos*11 + 10+ offset].find("-")]); self.data.append(self.companyValue); self.companyValues.append(self.companyValue)
#                self.read = True;
#                pos = pos + 1
#                if pos * 11 + 1 >= len(lines):
#                    break
#            return True;
#        except: 
##            print filename, "not found"
#            return False
#        return True
    def parseSaveFileResult(self, filename):
        try:
            file = open(filename)
            lines = file.readlines()
            pos = 0
            offset = 0
            lpc = linesPerCompany = 22;
            while(True):
                offset = 0
                line = (string.split(lines[pos*lpc + 1 + offset], ":")[1]).strip();
                self.companyId = string.atoi(line); self.data.append(self.companyId); self.companyIds.append(self.companyId)
                offset = offset + 1;
                print self.companyId;
                
                line = (string.split(lines[pos*lpc + 1 + offset], ":")[1]).strip();
                companyName = line;
                offset = offset + 1;
                print companyName;
                
                line = (string.split(lines[pos*lpc + 1 + offset], ":")[1]).strip();
                self.totalVehicle = string.atoi(line); self.data.append(self.totalVehicle); self.totalVehicles.append(self.totalVehicle)
                offset = offset + 1;
                print self.totalVehicle;
                
                line = (string.split(lines[pos*lpc + 1 + offset], ":")[1]).strip();
                self.totalProfitingVehicle = string.atoi(line);self.data.append(self.totalProfitingVehicle);self.totalProfitingVehicles.append(self.totalProfitingVehicle)
                offset = offset + 1;
                print self.totalProfitingVehicle;
                
                line = (string.split(lines[pos*lpc + 1 + offset], ":")[1]).strip();
                self.service_station = string.atoi(line); self.data.append(self.service_station);self.service_stations.append(self.service_station)
                offset = offset + 1;
                print self.service_station
                
                line = (string.split(lines[pos*lpc + 1 + offset], ":")[1]).strip();
                self.min_income = string.atoi(line); self.data.append(self.min_income);self.min_incomes.append(self.min_income)
                offset = offset + 1;
                print self.min_income
                
                line = (string.split(lines[pos*lpc + 1 + offset], ":")[1]).strip();
                self.max_income = string.atoi(line); self.data.append(self.max_income);self.max_incomes.append(self.max_income)
                offset = offset + 1;
                print self.max_income;
                
                line = (string.split(lines[pos*lpc + 1 + offset], ":")[1]).strip();
                self.cargo_delivered = string.atoi(line); self.data.append(self.cargo_delivered);self.cargo_delivereds.append(self.cargo_delivered)
                offset = offset + 1;
                print self.cargo_delivered;
                
                line = (string.split(lines[pos*lpc + 1 + offset], ":")[1]).strip();
                self.score_cargo = string.atoi(line); self.data.append(self.score_cargo);self.score_cargos.append(self.score_cargo)
                offset = offset + 1;
                print self.score_cargo;
                
                line = (string.split(lines[pos*lpc + 1 + offset], ":")[1]).strip();
                self.score_money = string.atoi(line); self.data.append(self.score_money);self.score_moneys.append(self.score_money)
                offset = offset + 1;
                print self.score_money;
                
                line = (string.split(lines[pos*lpc + 1 + offset], ":")[1]).strip();
                self.score_loan = string.atoi(line); self.data.append(self.score_loan); self.score_loans.append(self.score_loan)
                offset = offset + 1;
                print self.score_loan;
                
                line = (string.split(lines[pos*lpc + 1 + offset], ":")[1]).strip();
                self.score_total = string.atoi(line); self.data.append(self.score_total); self.score_totals.append(self.score_total)
                offset = offset + 1;
                print self.score_total;
                
                line = (string.split(lines[pos*lpc + 1 + offset], ":")[1]).strip();
                self.companyValue = string.atoi(line); self.data.append(self.companyValue); self.companyValues.append(self.companyValue)
                offset = offset + 1;
                print self.companyValue;

                line = (string.split(lines[pos*lpc + 1 + offset], ":")[1]).strip();
                self.year = string.atoi(line); self.data.append(self.year); self.years.append(self.year)
                offset = offset + 1;
                print self.year;
                
                line = (string.split(lines[pos*lpc + 1 + offset], ":")[1]).strip();
                self.loan = string.atoi(line); self.data.append(self.loan); self.loans.append(self.loan)
                offset = offset + 1;
                print self.loan;
                
                line = (string.split(lines[pos*lpc + 1 + offset], ":")[1]).strip();
                self.train = string.atoi(line); self.data.append(self.train); self.trains.append(self.train)
                offset = offset + 1;
                print self.train;
                
                line = (string.split(lines[pos*lpc + 1 + offset], ":")[1]).strip();
                self.lorry = string.atoi(line); self.data.append(self.lorry); self.lorries.append(self.lorry)
                offset = offset + 1;
                print self.lorry;
                
                line = (string.split(lines[pos*lpc + 1 + offset], ":")[1]).strip();
                self.bus = string.atoi(line); self.data.append(self.bus); self.busses.append(self.bus)
                offset = offset + 1;
                print self.bus
                
                line = (string.split(lines[pos*lpc + 1 + offset], ":")[1]).strip();
                self.plane = string.atoi(line); self.data.append(self.plane); self.planes.append(self.plane)
                offset = offset + 1;
                print self.plane;
                
                line = (string.split(lines[pos*lpc + 1 + offset], ":")[1]).strip();
                self.ship = string.atoi(line); self.data.append(self.ship); self.ships.append(self.ship)
                offset = offset + 1;
                print self.ship
                
                self.read = True;
                pos = pos + 1
#                print pos * lpc
#                print len(lines);
                if pos * lpc - 1> len(lines):
                    break
        except: 
#            print filename, "not found"
            return False
        return True

def parseSaveFileResults(expName, factor, expId =0, pos = 8, forcePath = "", multiCompany=False, whichYear=0, whichCompany=-1):
    path = cf.getAutoSavePath(expName)
    if forcePath !="":
        path = forcePath
    data = []
    addon = ""
    if expId != 0:
        addon = "%d_"%expId
    filenameTemplate = addon + expName + "_%d_"%factor  
    t = [] 
    for file in os.listdir(path):
        if file.find(filenameTemplate) <0 or file.endswith("sav.txt") == False or file.find("autosave%d.sav"%whichYear)<=0:
            continue
        
        sr = SaveFileResult()
        sr.parseSaveFileResult(os.path.join(path, file))
#        print len(sr.data)
#        print sr.data
#        print file, sr.datas[pos]
        if multiCompany==False:
            t.append(sr.data[pos])
        else:
            if whichCompany == -1:
                t.extend(sr.datas[pos])
            else:
                t.append(sr.datas[pos][whichCompany])
    return t

def parseSaveFileResultsAll(expName, expId =0, pos = 10, multiCompany=False, whichYear=0, whichCompany=-1):
    path = cf.getAutoSavePath(expName)
    print "The path to store save file is ", path
    data = []
    for factor in DescriptionParser.getFactors(expName):
        data.append(parseSaveFileResults(expName, factor, expId, pos, "", multiCompany,whichYear,whichCompany))
    return data

def checkSaveGameCorrect(expName, factor, expect, expId = 0):
    path = cf.getAutoSavePath(expName)
    addon = ""
    if expId != 0:
        addon = "%d_"%expId
    filenameTemplate = addon + expName + "_%d_"%factor  
    total = 0
    year = cf.getAutoSaveYear(expName)
    for file in os.listdir(path):
        if file.find(filenameTemplate) <0 or file.endswith("_companyScore.txt") == False or file.find("autosave%d"%year)<0:
            continue
#        ParseTheMapUsingOpenTTDExecutable.getCompanyScore(os.path.join(path,file))
        print file
        sr = SaveFileResult()
        ret= sr.parseSaveFileResult(os.path.join(path,file))
        if ret == True:
            total = total + 1
    return expect - total

def checkSaveGameCorrectAll(expName, expId = 0):
    path = cf.getAutoSavePath(expName)
    for factor in range(DescriptionParser.getMinVarOfExp(expName), DescriptionParser.parseConfigureFile(expName)):
        checkSaveGameCorrect(expName, factor, expId)
    


if __name__ == "__main__":
    filename = "c:\\Unnamed, 1950-01-25.sav.txt";
    sf = SaveFileResult();
    sf.parseSaveFileResult(filename);
